<?php
/**
 * Created by PhpStorm.
 * User: ownfi
 * Date: 2017-04-20
 * Time: 17:42
 */

namespace App\Services\Impl;


use App\Common\Constant\Params;
use App\Common\Constant\Status;
use App\Models\Coupon;
use App\Models\CouponGrantList;
use App\Models\Merchant;
use App\Services\ICouponService;
use App\Services\ISystemService;
use Auth;
use Carbon\Carbon;
use DB;
use Log;

class CouponServiceImpl implements ICouponService
{
    public function all(array $wheres = [])
    {
        $model = Coupon::alias('t1')->select('t1.*')->orderBy('t1.c_add_time','DESC');
        return $model->paginate(config('common.perpage'));
    }

    public function getCoupleList()
    {
        return Coupon::alias('t1')->select('t1.c_id','t1.c_name')->orderBy('t1.c_add_time','DESC')->get()->pluck('c_name','c_id');
    }

    public function receiveList(array $wheres = [])
    {
        $model = CouponGrantList::alias('t1')->select('t1.*')->orderBy('t1.cg_add_time','DESC');
        if ($wheres){
            foreach ($wheres as $where){
                if ($where[0] == 'me_username'){
                    $model->join(Merchant::table().' as m', function ($join) use ($where){
                        $join->on('t1.cg_meid', '=', 'm.me_id')
                            ->where([$where]);
                    });
                }else{
                    $model->where([$where]);
                }
            }
        }
        return $model->paginate(config('common.perpage'));
    }

    public function create($vaildtype, $name, $vaildday, $starttime, $endtime, $money, $fullmoney, $count, $stoptime)
    {
        $data = [
            'c_name'=>$name,
            'c_vaildtype'=>$vaildtype,
            'c_fullmoney'=>$fullmoney,
            'c_money'=>$money,
            'c_count'=>$count,
            'c_stoptime'=>strtotime($stoptime),
            'c_grantuser'=>Auth::user()->name
        ];

        if ($vaildtype == Params::COUPON_VAILDTYPE_DAYS){
            $data['c_vaildday'] = $vaildday;
        }else if ($vaildtype == Params::COUPON_VAILDTYPE_PERIOD){
            $data['c_starttime'] = strtotime($starttime);
            $data['c_endtime'] = strtotime($endtime);
        }

        return Coupon::create($data);
    }

    public function edit($coupon_id,$vaildtype, $name, $vaildday, $starttime, $endtime, $money, $fullmoney, $count, $stoptime)
    {
        $model = Coupon::find($coupon_id);
        if (!$model){
            Log::error(sprintf('%s/%s::%s[%d] %s',__NAMESPACE__,__CLASS__,__FUNCTION__,__LINE__-2,'miss coupon'));
            return false;
        }
        $data = [
            'c_name'=>$name,
            'c_vaildtype'=>$vaildtype,
            'c_fullmoney'=>$fullmoney,
            'c_money'=>$money,
            'c_count'=>$count,
            'c_stoptime'=>strtotime($stoptime),
            'c_grantuser'=>Auth::user()->name
        ];

        if ($vaildtype == Params::COUPON_VAILDTYPE_DAYS){
            $data['c_vaildday'] = $vaildday;
            $data['c_starttime'] = null;
            $data['c_endtime'] = null;
        }else if ($vaildtype == Params::COUPON_VAILDTYPE_PERIOD){
            $data['c_starttime'] = strtotime($starttime);
            $data['c_endtime'] = strtotime($endtime);
            $data['c_vaildday'] = null;
        }

        return $model->update($data);
    }

    public function assign($merchant_id, $coupon_id, $count)
    {
        $coupon = Coupon::find($coupon_id);
        if (!$coupon){
            Log::error(sprintf('%s/%s::%s[%d] %s',__NAMESPACE__,__CLASS__,__FUNCTION__,__LINE__-2,'miss coupon'));
            return false;
        }

        if (empty($coupon->c_count) || ($coupon->c_count < $count)){
            return Status::COUPON_NOT_ENOUGH;
        }

        $data = [
            'cg_cid'=>$coupon_id,
            'cg_meid'=>$merchant_id,
            'cg_grantuser'=>@Auth::user()->name,
        ];
        if ($coupon->c_vaildtype == Params::COUPON_VAILDTYPE_DAYS){
            $data['cg_starttime'] = Carbon::now()->timestamp;
            $data['cg_endtime'] = Carbon::now()->addDays($coupon->c_vaildday)->timestamp;
        }else{
            $data['cg_starttime'] = $coupon->c_starttime->timestamp;
            $data['cg_endtime'] = $coupon->c_endtime->timestamp;
        }

        $success_count = 0;
        for ($i = 0;$i < $count;$i++){
            $data['cg_number'] = resolve(ISystemService::class)->genCouponNumber();
            $ret = CouponGrantList::create($data);
            if ($ret){
                $success_count++;
            }
        }
        $coupon->update(['c_count'=>DB::raw("c_count - {$success_count}")]);
        return $success_count;
    }

}